package com.marlonmafra.android.widget;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import com.google.android.material.tabs.TabLayout;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.efounder.mobilecomps.R;
import com.efounder.utils.JfResourceUtil;
import com.efounder.view.EFTextView;
import com.marlonmafra.android.widget.utils.FontCache;
import com.marlonmafra.android.widget.utils.Utils;
import com.utilcode.util.SizeUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


public class SegmentedTab extends TabLayout {

    private int tabSelectedColor;
    private int tabUnselectedColor;
    private ColorStateList titleColor;
    private int titleTextSize = 16;
    private Typeface typeface;
    private int borderColorSelected;
    private int borderColorUnselected;

    private List<String> titles = new ArrayList<>();

    public SegmentedTab(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    public SegmentedTab(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    private void init(AttributeSet attrs) {

        //setSelectedTabIndicatorColor(ContextCompat.getColor(getContext(), android.R.color.transparent));
        setTabMode(TabLayout.MODE_FIXED);
        setTabGravity(TabLayout.GRAVITY_FILL);

        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.SegmentedTab);
            this.tabSelectedColor = typedArray.getColor(R.styleable.SegmentedTab_tabSelectedColor, ContextCompat.getColor(getContext(), R.color.white));
//            this.tabUnselectedColor = typedArray.getColor(R.styleable.SegmentedTab_tabUnselectedColor, JfResourceUtil.getSkinColor(R.color.title_Background));
            //使用透明背景色，这样看起来协调 TODO yqs  20191108
            this.tabUnselectedColor = typedArray.getColor(R.styleable.SegmentedTab_tabUnselectedColor, JfResourceUtil.getSkinColor(R.color.transparent));

            if (typedArray.hasValue(R.styleable.SegmentedTab_titleColor)) {
                this.titleColor = typedArray.getColorStateList(R.styleable.SegmentedTab_titleColor);
            } else {
//                this.titleColor = ContextCompat.getColorStateList(getContext(), R.color.segment_control_title);
                this.titleColor = JfResourceUtil.getSkinColorStateList(R.color.segment_control_title);

            }

            this.titleTextSize = typedArray.getDimensionPixelSize(R.styleable.SegmentedTab_titleTextSize, this.titleTextSize);

            this.borderColorSelected = typedArray.getColor(R.styleable.SegmentedTab_borderColorSelected, this.tabUnselectedColor);
            this.borderColorUnselected = typedArray.getColor(R.styleable.SegmentedTab_borderColorUnselected, this.tabSelectedColor);

            String path = typedArray.getString(R.styleable.SegmentedTab_titleFontPath);
            if (path != null) {
                this.typeface = FontCache.getInstance().put(path, getContext().getAssets());
            }
            typedArray.recycle();
        }

        disablePadding("tabPaddingStart");
        disablePadding("tabPaddingEnd");
    }

    public void setup(List<String> titles) {

        if (titles.size() <= 1) {
            throw new IllegalArgumentException("You need at least two tabs");
        }
        this.titles.clear();
        this.titles.addAll(titles);
        for (int i = 0; i < getTabCount(); i++) {
            Tab tab = getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(i, titles));
            }

        }

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) getLayoutParams();
        //layoutParams.setMargins(Utils.getValueByDensity(getContext(), 10), layoutParams.topMargin, Utils.getValueByDensity(getContext(), 10), layoutParams.bottomMargin);
    }

    private View getTabView(int position, List<String> titles) {
        com.marlonmafra.android.widget.TabView tab;

        if (position == 0) {
            tab = new LeftTabView(getContext(), R.layout.left_tab);
        } else if (position == titles.size() - 1) {
            tab = new RightTabView(getContext(), R.layout.right_tab);
        } else {
            tab = new CenterTabView(getContext(), R.layout.center_tab);
        }

        tab.setBackground(this.tabSelectedColor, this.tabUnselectedColor, this.borderColorSelected, this.borderColorUnselected);
        tab.setTitle(titles.get(position));
        tab.setTextSize(this.titleTextSize);
        tab.setTextColorState(this.titleColor);

        if (this.typeface != null) {
            tab.setTitleTypeFace(this.typeface);
        }

        return tab.getView();
    }

    private void disablePadding(String name) {
        try {
            Field mTabPaddingStart = TabLayout.class.getDeclaredField(name);
            mTabPaddingStart.setAccessible(true);
            mTabPaddingStart.setInt(this, Utils.getValueByDensity(getContext(), -0.5));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    //20180724自定义方法

    //隐藏所有的下拉箭头显示
    public void hideAllDropDownArrow() {
        for (int i = 0; i < getTabCount(); i++) {
            Tab tab = getTabAt(i);
            if (tab.getCustomView() == null) {
                return;
            }
            tab.getCustomView().findViewById(R.id.iv_arrow).setVisibility(View.GONE);

            EFTextView efTextView = tab.getCustomView().findViewById(R.id.txtTitle);
            efTextView.getLayoutParams().width = RelativeLayout.LayoutParams.MATCH_PARENT;
            efTextView.setPadding(SizeUtils.dp2px(4), efTextView.getPaddingTop(),
                    SizeUtils.dp2px(4), efTextView.getPaddingBottom());
        }
    }

    //显示指定的下拉箭头
    public void showArrow(int position) {
        if (position < getTabCount()) {
            Tab tab = getTabAt(position);
//            RelativeLayout relativeLayout = (RelativeLayout) tab.getCustomView();
            EFTextView efTextView = tab.getCustomView().findViewById(R.id.txtTitle);
            ImageView imageView = tab.getCustomView().findViewById(R.id.iv_arrow);
            imageView.setVisibility(View.VISIBLE);

            efTextView.setPadding( SizeUtils.dp2px(2), efTextView.getPaddingTop(),
                    SizeUtils.dp2px(1), efTextView.getPaddingBottom());

//            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) efTextView.getLayoutParams();
//            params.addRule(RelativeLayout.ALIGN_PARENT_START);
//            params.addRule(RelativeLayout.CENTER_VERTICAL);

            //对箭头着色
            tintDrawable(imageView.getDrawable(), JfResourceUtil.getSkinColor(R.color.title_Background));
        }
    }

    private Drawable tintDrawable(Drawable drawable, int colors) {
        final Drawable wrappedDrawable = DrawableCompat.wrap(drawable).mutate();
        DrawableCompat.setTint(wrappedDrawable, colors);
        return wrappedDrawable;
    }
}
